package com.ruoyi.web.controller.consrecording;

import java.io.IOException;
import java.util.List;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.domain.ActualMaterial;
import com.ruoyi.domain.ThisStock;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.service.IActualMaterialService;
import com.ruoyi.service.IThisStockService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.ConstructionRecording;
import com.ruoyi.service.IConstructionRecordingService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 施工日志Controller
 *
 * @author ruoyi
 * @date 2020-07-07
 */
@Controller
@RequestMapping("/ruoyi/recording")
public class ConstructionRecordingController extends BaseController {
    private String prefix = "ruoyi/recording";

    @Autowired
    private IConstructionRecordingService constructionRecordingService;

    @Resource
    private IThisStockService thisStockService;

    @Autowired
    private IActualMaterialService actualMaterialService;

    @RequiresPermissions("ruoyi:recording:view")
    @GetMapping()
    public String recording() {
        return prefix + "/recording";
    }

    /**
     * 查询施工日志列表
     */
    @RequiresPermissions("ruoyi:recording:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ConstructionRecording constructionRecording) {
        startPage();
        List<ConstructionRecording> list = constructionRecordingService.selectConstructionRecordingList(constructionRecording);
        return getDataTable(list);
    }


    /**
     * 查询总项目对应的施工日志列表
     */
    @RequiresPermissions("ruoyi:recording:list")
    @PostMapping("/lists")
    @ResponseBody
    public TableDataInfo lists(Long sid) {
        startPage();
        List<ConstructionRecording> list = constructionRecordingService.selectConstructionRecordingLists(sid);
        return getDataTable(list);
    }

    /**
     * 导出施工日志列表
     */
    @RequiresPermissions("ruoyi:recording:export")
    @Log(title = "施工日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ConstructionRecording constructionRecording) {
        List<ConstructionRecording> list = constructionRecordingService.selectall(constructionRecording);
        ExcelUtil<ConstructionRecording> util = new ExcelUtil<ConstructionRecording>(ConstructionRecording.class);
        return util.exportExcel(list, "recording");
    }

    /**
     * 新增施工日志
     */
    @GetMapping("/add/{pId}")
    public String add(@PathVariable("pId") Long pId, ModelMap map) {
        map.put("pId", pId);
        List<ThisStock> thisStockList = thisStockService.selectThisStockLists(pId);
        map.put("thisStockList",thisStockList);
        return prefix + "/add";
    }

    /**
     * 新增保存施工日志
     */
    @RequiresPermissions("ruoyi:recording:add")
    @Log(title = "施工日志", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file,ConstructionRecording constructionRecording,ModelMap map) throws IOException {

        ThisStock thisStock = new ThisStock();
        //获取用户的外键id
        long a = constructionRecording.getcPid();
        //获取用户选择的材料
        String tname = constructionRecording.getcTname();
        //查询本厂库存有没有用户用的材料
        ThisStock thisStock1 = thisStockService.selectThisStockByIds(a, tname);

        if (constructionRecording.getcTnum()>thisStock1.gettNum()){
            return AjaxResult.error("输入的数量大于本场库存");
        }else{
            long num = (thisStock1.gettNum()-constructionRecording.getcTnum());
            thisStockService.updateThisStocks(num, tname);
        }
        String name = ShiroUtils.getLoginName();
        constructionRecording.setcHeir(name);
        //上传文件路径
        String filePach = Global.getUploadPath();
        //上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePach, file);
        constructionRecording.setcFile(fileName);


        //
        ActualMaterial am = new ActualMaterial();
        //按材料名称查询数据库中的数据
        ActualMaterial actualMaterial =  actualMaterialService.selectanme(tname);
        //判断如果数据库里没有这条数据就调用insert方法.
        if (actualMaterial==null){
                am.setcPname(tname);
                am.setcPnum(constructionRecording.getcTnum());
                am.setcCid(a);
                actualMaterialService.insertActualMaterial(am);
        //如果数据库中有就调用update方法更新.
        }else{
            if(a!=actualMaterial.getcCid()){
                am.setcPname(tname);
                am.setcPnum(constructionRecording.getcTnum());
                am.setcCid(a);
                actualMaterialService.insertActualMaterial(am);
            }else{
                am.setcPnum(actualMaterial.getcPnum()+constructionRecording.getcTnum());
                am.setcPname(tname);
                actualMaterialService.updateActualMaterial(am);
            }

        }
        return toAjax(constructionRecordingService.insertConstructionRecording(constructionRecording));
    }

    /**
     * 修改施工日志
     */
    @GetMapping("/edit/{cId}")
    public String edit(@PathVariable("cId") Long cId, ModelMap mmap) {
        ConstructionRecording constructionRecording = constructionRecordingService.selectConstructionRecordingById(cId);
        mmap.put("constructionRecording", constructionRecording);
        return prefix + "/edit";
    }

    /**
     * 修改保存施工日志
     */
    @RequiresPermissions("ruoyi:recording:edit")
    @Log(title = "施工日志", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ConstructionRecording constructionRecording) {
        return toAjax(constructionRecordingService.updateConstructionRecording(constructionRecording));
    }

    /**
     * 删除施工日志
     */
    @RequiresPermissions("ruoyi:recording:remove")
    @Log(title = "施工日志", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(constructionRecordingService.deleteConstructionRecordingByIds(ids));
    }

//   /* *//**
//     *
//     * 下载功能
//     *//*
//    @GetMapping("downloadFile")
//    public void resourceDownload(@PathVariable("pUploading") String fAccessory, HttpServletRequest request, HttpServletResponse response)
//            throws Exception {
//        // 本地资源路径
//        String localPath = Global.getProfile();
//        // 数据库资源地址
//        String downloadPath = localPath + StringUtils.substringAfter(fAccessory, Constants.RESOURCE_PREFIX);
//        // 下载名称
//        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("multipart/form-data");
//        response.setHeader("Content-Disposition",
//                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
//        FileUtils.writeBytes(downloadPath, response.getOutputStream());
//    }*/
}
